<template>
  <a-card :bordered="false" :loading="loading">
    <div class="w-full">
      <a-form
        class="m-t-10"
        :model="detailData"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
        @finish="onFinish"
        @finish-failed="onFinishFailed"
      >
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="景点名称" name="name">
              <a-input
                v-model:value="detailData.name"
                :rules="{ required: true, message: '请输入景点名称' }"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              label="封面"
              name="cover"
              :rules="{ required: true, message: '请添加封面' }"
            >
              <upload-image
                :image-str="detailData.cover"
                :component-props="{ maxCount: 1 }"
                upload="上传"
                :max-file-size-mb="4"
                @on-change-upload="(value) => (detailData.cover = value)"
              />
              <span class="text-hex-999">支持拓展名：.jpg.jpeg.png</span>
            </a-form-item>
          </a-col>
          <a-col :span="24" :pull="2">
            <a-form-item label="地点">
              <div class="w-full flex">
                <a-form-item
                  name="address"
                  class="flex-1 m-r-4"
                  :rules="{ required: true, message: '请添加地点' }"
                >
                  <a-input
                    ref="addressInput"
                    v-model:value="detailData.address"
                    class="address_input"
                    placeholder="请选择地点"
                    @click="mapModalVisible = true"
                  />
                </a-form-item>
                <a-form-item name="detailedAddress" class="flex-1">
                  <a-input
                    v-model:value="detailData.detailedAddress"
                    placeholder="可输入补充内容，如：3楼101室"
                  />
                </a-form-item>
              </div>
            </a-form-item>
          </a-col>
          <a-col :span="24" :pull="2">
            <a-form-item label="轮播图片" name="images">
              <upload-image
                :image-str="detailData.images"
                :component-props="{ maxCount: 5 }"
                upload="上传"
                :max-file-size-mb="4"
                @on-change-upload="(value) => (detailData.images = value)"
              />
              <span class="text-hex-999">支持拓展名：.jpg.jpeg.png</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="景点特色" name="feature">
              <a-textarea v-model:value="detailData.feature" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="价格" name="price">
              <a-input-number v-model:value="detailData.price" style="width: 200px" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <!--            <div class="inline-flex items-center whitespace-nowrap">-->
            <a-form-item
              label="景点类型"
              name="type"
              :rules="{ required: true, message: '请选择景点类型' }"
            >
              <a-select
                v-model:value="detailData.type"
                class="min-w-150px"
                allow-clear
                :options="typeList"
                placeholder="请选择景点类型"
              ></a-select>
            </a-form-item>
            <!--            </div>-->
          </a-col>
          <a-col :span="12">
            <a-form-item
              label="景点等级"
              name="grade"
              :rules="{ required: false, message: '请选择景点等级' }"
            >
              <a-select
                v-model:value="detailData.grade"
                class="min-w-150px"
                allow-clear
                :options="gradeList"
                placeholder="请选择景点等级"
              ></a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="排序" name="sort">
              <a-input v-model:value="detailData.sort" />
            </a-form-item>
          </a-col>
          <a-col :span="24" :pull="1">
            <a-form-item
              label="介绍"
              name="introduce"
              :label-col="{ span: 3 }"
              :wrapper-col="{ span: 21 }"
              :rules="{ required: true, message: '请输入介绍' }"
            >
              <tinymce-editor
                v-model:value="detailData.introduce"
                placeholder="详细介绍"
              ></tinymce-editor>
            </a-form-item>
          </a-col>
        </a-row>
        <!--          </a-row>-->
        <a-form-item :wrapper-col="{ span: 24 }">
          <div class="text-center">
            <a-button class="mr-50px" type="primary" html-type="submit">发布</a-button>
            <a-button @click="closeTab">返回</a-button>
          </div>
        </a-form-item>
      </a-form>
      <map-modal
        :visible="mapModalVisible"
        :selected-location="detailData.address"
        :center="[detailData.lng, detailData.lat]"
        @ok="onOk"
        @cancel="onCancel"
      />
    </div>
  </a-card>
</template>

<script setup lang="tsx">
  import { message } from 'ant-design-vue';
  import DynamicForm from '@/components/dynamicForm/index.vue';
  import useRequestDetail from '@/hooks/useRequestDetail';
  import { attractionsApi, createAttractions, updateAttractions } from '@/api/attractions';
  import { useTabsViewStore } from '@/store/modules/tabsView';
  import { ComponentsTypeEnum } from '@/enums/componentsEnum';
  import { categoryJsonByType } from '@/api/category';
  import { categoryTypeEnum } from '@/enums/categoryTypeEnum';
  import { formatToDateTime } from '@/utils/dateUtil';
  import { useUserStore } from '@/store/modules/user';

  defineOptions({
    name: 'attractionsEdit',
  });

  const format = 'YYYY-MM-DD HH:mm';
  const typeList = ref<{ id: number; name: string }[]>([]);
  const gradeList = ref<{ value: number; label: string }[]>([]);

  const userStore = useUserStore();
  const rustic = userStore.getRusticId();

  const router = useRouter();
  const route = useRoute();
  const tabsViewStore = useTabsViewStore();
  const mapModalVisible = ref<boolean>(false);
  const { detailData, loading } = useRequestDetail({
    apiKey: attractionsApi.attractionsDetail,
    initParams: route?.query,
    isMount: !!Object.values(route?.query).length && !!Object.values(route?.query)[0],
  });
  const submitForm = async (params) => {
    const attractionsId = route?.query?.id;
    const res = attractionsId
      ? await updateAttractions({
          ...params,
          id: attractionsId,
          rusticId: rustic,
        })
      : await createAttractions({
          ...params,
          rusticId: rustic,
        });
    if (res) {
      message.success(res?.msg);
      closeTab();
    }
  };

  const closeTab = () => {
    tabsViewStore.closeCurrentTab(route);
  };

  const getCategoryList = async () => {
    const res = await categoryJsonByType({ type: categoryTypeEnum.ATTRACTION_TYPE });
    if (res) {
      typeList.value = res.data.map((item: { name: string; id: number }) => ({
        label: item.name,
        value: item.id,
      }));
    }
    const gradeRes = await categoryJsonByType({ type: categoryTypeEnum.ATTRACTION_GRADE });
    if (gradeRes) {
      gradeList.value = gradeRes.data.map((item: { name: string; id: number }) => ({
        label: item.name,
        value: item.id,
      }));
      // 添加额外的元素到数组开头
      gradeList.value.unshift({ label: '无', value: 0 });
    }
  };

  const onFinish = (values: any) => {
    submitForm(detailData.value);
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  const onOk = (data: any) => {
    // console.info('modalData ==>,', data);
    detailData.value = { ...detailData.value, ...data };
    detailData.value.address = data.location;
    detailData.value.lng = data.lng;
    detailData.value.lat = data.lat;
  };
  const onCancel = () => {
    mapModalVisible.value = false;
  };

  onMounted(() => {
    getCategoryList();
  });
</script>

<style></style>
